<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-04-03
 * Time: 1:04
 */

namespace App\Services\Impl;


use App\Common\Constant\CacheKey;
use App\Common\Constant\Params;
use App\Models\Master;
use App\Models\MasterDetail;
use App\Models\MasterStatistic;
use App\Models\MasterWallet;
use App\Models\Merchant;
use App\Services\IAreaService;
use App\Services\ICacheService;
use App\Services\ICookieService;
use App\Services\IManagerService;
use App\Services\IMasterService;
use App\Services\IMerchantService;
use App\Services\IStorageService;
use App\Services\Request;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Collection;
use Log;

class MasterServiceImpl implements IMasterService
{
    private $cacheService;
    private $storageService;
    private $areaService;

    /**
     * MasterServiceImpl constructor.
     */
    public function __construct(ICacheService $cacheService,IStorageService $storageService,IAreaService $areaService)
    {
        $this->cacheService = $cacheService;
        $this->storageService = $storageService;
        $this->areaService = $areaService;
    }

    public function add($weixinUserId,$phoneNum,$realName,$idcardNum,$baseAreaId,array $serviceAreaIds,$serviceCategory,array $serviceTypes,$idcardFront,$idcardBack,$idcardHold){
        //防止重复注册
        if ($weixinUserId){
            $master = Master::where('weixin_userid',$weixinUserId)->first();
        }else{
            $master = Master::where('phone',$phoneNum)->first();
        }
        if ($master){
            Log::error(sprintf('%s/%s::%s[%d] %s',__NAMESPACE__,__CLASS__,__FUNCTION__,__LINE__-2,'master already exists'));
            return false;
        }

//        list($idcardFront,$idcardBack,$idcardHold) = $this->weixinService->getMedia([$idcardFront,$idcardBack,$idcardHold]);

        $master = Master::create([
            'weixin_userid' => $weixinUserId,
            'phone' => $phoneNum,
            'real_name' => $realName,
            'idcard' => $idcardNum,
            'area_id' => $baseAreaId,
            'area_text' => $this->areaService->getAreaCrumbById($baseAreaId),
            'service_area_ids' => $serviceAreaIds,
            'service_category' => $serviceCategory,
            'service_type' => $serviceTypes,
            'idcard_front' => $idcardFront,
            'idcard_back' => $idcardBack,
            'idcard_hold' => $idcardHold,
            'status' => Params::USER_STATUS_REVIEW
        ]);
        if (!$master){
            Log::error(sprintf('%s/%s::%s[%d] %s',__NAMESPACE__,__CLASS__,__FUNCTION__,__LINE__-2,'master create fail'));
            return false;
        }
        $ret = MasterDetail::create([
                'master_id' => $master->id
            ])
            && MasterWallet::create([
                'master_id' => $master->id
            ])
            && MasterStatistic::create([
                'master_id' => $master->id
            ]);
        if (!$master){
            Log::error(sprintf('%s/%s::%s[%d] %s',__NAMESPACE__,__CLASS__,__FUNCTION__,__LINE__-2,'master info create fail'));
            return false;
        }

        return $master;
    }

    public function all(array $wheres = [])
    {
        $model = Master::alias('t1')->select('t1.*')->orderBy('t1.add_time','DESC')->with(['detail','wallet']);
        if ($wheres){
            foreach ($wheres as $where){
                if ($where[0] == 'assure_fund'){
                    $model->join(MasterWallet::table().' as w', function ($join) use ($where){
                        $join->on('t1.id', '=', 'w.master_id');
                        $column = 'assure_fund';
                        if ($where[2]){//已缴纳
                            $join->where(function ($query) use ($column){
                                $query->whereNotNull($column)
                                    ->where($column,'<>','');
                            });
                        }else{//未缴纳
                            $join->where(function ($query) use ($column){
                                $query->whereNull($column)
                                    ->orWhere($column,'');
                            });
                        }
                    });
                }else if ($where[0] == 'pass'){
                    $model->where('t1.status',$where[2]);
                }else if ($where[0] == 'disable'){
                    $model->where('t1.status',$where[2]);
                }else if ($where[0] == 'head_change_to'){
                    $model->join(MasterDetail::table().' as d', function ($join) use ($where){
                        $join->on('t1.id', '=', 'd.master_id');
                        $column = 'd.head_chang_to';
                        if ($where[2]){//已审核
                            $join->where(function ($query) use ($column){
                                $query->whereNull($column)
                                    ->orWhere($column,'');
                            });
                        }else{//未审核
                            $join->where(function ($query) use ($column){
                                $query->whereNotNull($column)
                                    ->where($column,'<>','');
                            });
                        }
                    });
                }else{
                    $model->where('t1.'.$where[0],$where[1],$where[2]);
                }
            }
        }
        return $model->paginate(config('common.perpage'));
    }

    public function registerPass($master_id)
    {
        $master = Master::find($master_id);
        $master->status = Params::USER_STATUS_NORMAL;
        return $master->save() && $this->cacheService->del(CacheKey::currentUserKey($master->weixin_userid));
    }

    public function headimgPass($master_id)
    {
        $detail = MasterDetail::where('master_id',$master_id)->first();

        $master = Master::find($master_id);
        $master->head_img = $detail->head_chang_to;

        $detail->head_chang_to = '';

        return $master->save() && $detail->save() && $this->cacheService->currentUser($master->weixin_userid,$master);
    }

    public function disable($master_id,$disable_type,$disable_time = null)
    {
        $master = Master::find($master_id);
        $master->status = Params::USER_STATUS_STOP;
        if ($disable_type == Params::DISABLE_TEMPORARY){
            $master->disable_time = Carbon::now()->addDays($disable_time ? : config('common.disable_temporary_default'))->timestamp;
        }
        return $master->save() && $this->cacheService->currentUser($master->weixin_userid,$master);
    }

    public function enable($master_id)
    {
        $master = Master::find($master_id);
        $master->status = Params::USER_STATUS_NORMAL;
        $master->disable_time = null;
        return $master->save() && $this->cacheService->currentUser($master->weixin_userid,$master);
    }

    public function transformMerchantServiceType($merchant_service_type)
    {
        $master_service_type = [];
        Collection::make((array)$merchant_service_type)->each(function($item, $key) use(&$master_service_type){
            $transform = [
                Params::MERCHANT_SERVICE_TYPE_DELIVERY_INSTALL=>[Params::SERVICE_TYPE_DELIVERY,Params::SERVICE_TYPE_INSTALL],
                Params::MERCHANT_SERVICE_TYPE_INSTALL=>[Params::SERVICE_TYPE_INSTALL],
                Params::MERCHANT_SERVICE_TYPE_REPAIR=>[Params::SERVICE_TYPE_REPAIR],
                Params::MERCHANT_SERVICE_TYPE_DELIVERY=>[Params::SERVICE_TYPE_DELIVERY],
                Params::MERCHANT_SERVICE_TYPE_PACK_RETURN=>[Params::SERVICE_TYPE_DELIVERY],
            ];
            $master_service_type = array_merge($master_service_type,$transform[$item]);
        });
        sort($master_service_type);
        return array_unique($master_service_type);
    }

    public function delete($master_id)
    {
        $master = Master::find($master_id);
        return $master->delete() && $this->cacheService->del(CacheKey::currentUserKey($master->weixin_userid));
    }
}